package redis

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/baizhige/go-server-tempalte/common/log"
	"github.com/redis/go-redis/v9"
	"time"
)

var ErrNotFound = errors.New("not found")
var DuplicateKeys = errors.New("duplicate Keys")

func Set(key string, obj interface{}, expire time.Duration) (err error) {
	var value string
	switch v := obj.(type) {
	case string:
		value = v
	case []byte:
		value = string(v)
	case int, int8, int16, int32, int64:
		value = fmt.Sprintf("%d", v)

	default:
		bs, e := json.Marshal(obj)
		if e != nil {
			err = e
			return
		}
		value = string(bs)
	}
	err = cluster.Set(context.Background(), key, value, expire).Err()
	return
}

func SetNX(key string, obj interface{}, expire time.Duration) (err error) {
	var value string
	switch v := obj.(type) {
	case string:
		value = v
	case []byte:
		value = string(v)
	case int, int8, int16, int32, int64:
		value = fmt.Sprintf("%d", v)

	default:
		bs, e := json.Marshal(obj)
		if e != nil {
			err = e
			return
		}
		value = string(bs)
	}
	res, err := cluster.SetNX(context.Background(), key, value, expire).Result()
	if err != nil {
		log.Error(err)
		return err
	} else if !res {
		return DuplicateKeys
	}
	return
}
func Expire(key string, expire time.Duration) (err error) {
	ctx := context.Background()
	err = cluster.Expire(ctx, key, expire).Err()
	return
}
func Get(key string) (ret string, err error) {
	v := cluster.Get(context.Background(), key)
	if errors.Is(v.Err(), redis.Nil) {
		err = ErrNotFound
		return
	}
	if v.Err() != nil {
		err = v.Err()
		return
	}
	ret = v.Val()
	return
}

func Del(key string) (err error) {
	err = cluster.Del(context.Background(), key).Err()
	return
}
